import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common";
import { wrappedRowSelection } from 'components/table/table-row-selection'
import { Form, Button, message, Tabs, Badge, Popconfirm, Modal } from 'antd'
const TabPane = Tabs.TabPane;
const confirm = Modal.confirm;
import errorMessage from "share/errorMessage";
import "styles/setting/workflow-config/new-workflow-config.scss"
import AdvancedTable from 'components/advanced-table'
const SimpleTable = AdvancedTable.SimpleTable;
import  EditCondition from 'containers/setting/workflow-matrix/edit-condition'
import  NewMatrixCondition from 'containers/setting/workflow-matrix/new-matrix-condition'
import SlideFrame from 'components/slide-frame'
import "styles/setting/workflow-matrix/matrix-detail.scss"
import workflowMatrixService from 'containers/setting/workflow-matrix/workflow-matrix.service';
import moment from "moment/moment";
import Importer from "components/template/importer/index";
import ExportModal from 'components/template/export-modal/export-modal';
import Space from "components/space"
import NumberRange from "containers/financial-management/expense-view/component/number-range";
import { chnNumChar } from 'containers/setting/new-workflow/utils'
import selectorData from "share/selectorData"

const symbolScopeMap = {
  9001: '>',
  9002: '>=',
  9003: '<',
  9004: '<=',
  9005: '='
}
class MatrixDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: props.params.tab,
      approvalMatrixParamsList: [],
      approvalMatrixColumnsList: [],
      searchForm: [],
      columns: [],
      selectedRowKeys: [],
      loading: false,
      tableConfig: {
        columns: [
          {
            dataIndex: 'index', title: messages('common.sequence')/*序号*/,
            width: 120,
            render: (text, record, index) => {
              return index + 1
            }
          }, {
            dataIndex: 'name', title: messages('request-4.key564')/*条件名称*/,
            render: text => text || '-',
          }, {
            width: 260,
            dataIndex: 'symbols', title: messages('request-4.key568')/*操作符*/,
            render: (text, record) => {
              return this.getSymbol(text)
            }
          }, {
            width: 260,
            dataIndex: 'status', title: messages('common.column.status')/*状态*/,
            render: value => {
              return <Badge status={value === 1 ? 'success' : 'error'}
                            text={value === 1 ? messages('request-4.key226')/*启用temp*/ : messages('request-4.key227')/*禁用temp*/}/>
            }
          }, {
            width: 260,
            title: messages('common.operation')/*操作*/, key: 'operation', render: (text, record) => (
              <div>
                {record.status === 1 ?
                  <Popconfirm
                    title={messages('request-4.key569')/*禁用条件维度将清空矩阵明细中对应列的数据，是否确定？*/}
                    onConfirm={(e) => {
                      e.stopPropagation();
                      this.handleChangeStatus(record)
                    }}
                  >
                    <a onClick={e => e.stopPropagation()}>{messages('request-4.key227')/*禁用temp*/ }</a>
                  </Popconfirm> :
                    (["cost_center_dimension1", "cost_center_dimension2","cost_center_dimension3","cost_center_dimension4",
                      "cost_center_dimension5","cost_center_dimension6","cost_center_dimension7"
                    ].includes(record.messageKey) && record.costCenterOID === null) ? (
                      <Popconfirm
                        title={messages('request-4.key570')/*启用此条件需要先设置条件对应的成本中心*/}
                        okText={messages('request-4.key571')/*去设置*/}
                        cancelText={messages('common.cancel')/*取消*/}
                        onConfirm={(e) => {this.handleEdit(messages('common.edit')/*编辑*/, record)}}
                      >
                        <a onClick={e => e.stopPropagation()}>{messages('request-4.key226')/*启用temp*/}</a>
                      </Popconfirm> ) : (
                      <a onClick={e => {
                        e.stopPropagation();
                        this.handleChangeStatus(record)
                      }}>{ messages('request-4.key226')/*启用temp*/}</a>)
                  }
              </div>
            )
          },
        ],
      },
    }
  }

  componentDidMount() {
    if (this.props.params.tab === 'detail') {
      let searchParams = {
        approvalMatrixId: this.props.params.id
      };
      workflowMatrixService.getDimensionList(searchParams)
        .then(res => {
          this.setState({
            approvalMatrixColumnsList: res.data.filter(item => item.status === 1)
          })
          this.onGetData(res.data)
        })
    }
  }

  onChangeTab = key => {
    this.setState({
      activeKey: key
    })
  };

  getSymbol = (symbols) => {
    switch(symbols) {
      case 9001:
        return '>';
        break;
      case 9002:
        return '>=';
        break;
      case 9003:
        return '<';
        break;
      case 9004:
        return '<=';
        break;
      case 9005:
        return '=';
        break;
      default:
        return '=';
        break;
    }
  };

  changeStatus = (e, record) => {
    //1启用状态 2禁用状态
    let params = {
      "approvalMatrixDimensionRlaId": record.approvalMatrixDimensionRlaId,
      "used": record.status === 2
    };
    e.stopPropagation();
    workflowMatrixService.postDimensionStatus(params)
      .then(res => {
        this.advancedTableRef.getList();
      })
      .catch(err => {
        errorMessage(err.response);
      })
  };

  service = (page, size) => {
    let searchParams = {
      approvalMatrixId: this.props.params.id
    };
    return workflowMatrixService.getDimensionList({ ...searchParams })
      .then(res => {
        this.setState({
          approvalMatrixColumnsList: res.data.filter(item => item.status === 1)
        })
        return res
      })
  };

  handleChangeStatus = record => {
    // record.status =  record.status
    let params = {
      approvalMatrixId: record.approvalMatrixId,
      used: record.status === 2,
      approvalMatrixDimensionRlaList: [
        {
          approvalMatrixDimensionId: record.approvalMatrixDimensionId,
          messageKey: record.messageKey
        }
      ]
    };
    workflowMatrixService.postDimensionStatus(params).then(res => {
        this.advancedTableRef.getList();
        message.success(record.status === 2 ? messages('request-4.key572')/*启用成功*/ : messages('request-4.key573')/*禁用成功*/)
      }).catch(err => {
        errorMessage(err.response);
      })
  }

  onGetDetailListData = () => {
    let { approvalMatrixColumnsList } = this.state;
  }

  serviceDetailList = (page, size, searchParams) => {
    // let searchParams = {
    //   approvalMatrixId: this.props.params.id
    // };
    let params = {
      page, size,
      priority: searchParams.priority,
      beginDate: searchParams.beginDate,
      endDate: searchParams.endDate,
      approvalMatrixId: this.props.params.id,
      approverOIDList: searchParams.approverOIDList,
    };
    let matrixRuleCondition = []
    for(let key in searchParams) {
      if (this.formatSearchForm(key)) {
        if (this.formatSearchForm(key).component === 'Chooser') {
          matrixRuleCondition.push({
            messageKey: key,
            values: searchParams[key]
          })
        } else if (this.formatSearchForm(key).component === 'Input') {
          matrixRuleCondition.push({
            messageKey: key,
            values: searchParams[key] ? [searchParams[key]] : null
          })
        } else if (this.formatSearchForm(key).id.indexOf('numberRange') > -1) {
          matrixRuleCondition.push({
            messageKey: key,
            valueBegin: searchParams[key] ? searchParams[key].valueBegin : null,
            valueEnd: searchParams[key] ? searchParams[key].valueEnd : null
          })
        }
      }
    }
    params.matrixRuleCondition = matrixRuleCondition;
    return workflowMatrixService.postMatrixDetailList({ page, size, ...params })
  }

  goBack = () => {
    window.history.go(-1);
  };

  handleEdit = (title, record) => {
    const costCenterKeys = [
      "cost_center_dimension1",
      "cost_center_dimension2",
      "cost_center_dimension3",
      "cost_center_dimension4",
      "cost_center_dimension5",
      "cost_center_dimension6",
      "cost_center_dimension7"
    ];
    const isCostCenter = costCenterKeys.includes(record.messageKey);
    let setOfBooksId = '';
    if (isCostCenter) {
      setOfBooksId = this.props.params.setOfBooksId;
    };

    let {} = this.state;
    SlideFrame.open({
      title: title || messages('request-4.key574')/*编辑条件维度*/,
      content: EditCondition,
      afterClose: this.afterCloseSlideFrame,
      params: {
        conditionDetail: record,
        setOfBooksId: setOfBooksId && setOfBooksId
      },
    }, this);
  }

  afterCloseSlideFrame = () => {
    this.advancedTableRef.getList();
  };

  afterCloseCreateFrame = () => {
    this.advancedDetailTableRef.getList()
  };

  handleCreate = (title, record, type) => {
    SlideFrame.open({
      title: title || messages('common.create')/*新建*/,
      content: NewMatrixCondition,
      afterClose: this.afterCloseCreateFrame,
      params: {
        type,
        setOfBooksId: this.props.params.setOfBooksId,
        approvalMatrixColumnsList: this.state.approvalMatrixColumnsList,
        approvalMatrixId: this.props.params.id,
        approvalMatrixRule: record,
      }
    }, this);
  }

  formatSearchForm = (messageKey, name) => {
    let searchFormOption = null;
    switch(messageKey) {
      case  'select_department':
      case 'default_user_department':
        searchFormOption = {
          component: 'Chooser',
          id: 'departmentOIDs' + messageKey,
          label: name,
          props: {
            type: 'department',
            labelKey: 'name',
            valueKey: 'departmentOid',
            single: true
          },
          dataIndex: messageKey,
          parser: value => ({
            [messageKey]: value ? value.map(item => item.departmentOid) : null
          }),
          JSONObjectFormatterParams: ['departmentName', 'departmentOID']
        };
        break;
      case 'default_user_applicant':
      case  'default_user_direct_leadership':
        searchFormOption = {
          component: 'Chooser',
          id: 'userOIDs' + messageKey,
          label: name,
          dataIndex: messageKey,
          props: {
            type: 'user_condition',
            labelKey: 'fullName',
            valueKey: 'userOID',
            listExtraParams: { roleType: 'TENANT' },
            dataIndex: 'approverName'
          },
          parser: value => ({
            [messageKey]: value ? value.map(item => item.userOID) : null
          }),
          JSONObjectFormatterParams: ['fullName', 'userOID']
        };
        break;
      case 'default_applicant_company':
        searchFormOption = {
          dataIndex: messageKey,
          component: 'Chooser',
          id: 'companyOIDs' + messageKey,
          label: name,
          props: {
            type: 'available_company',
            labelKey: 'name',
            valueKey: 'companyOID',
            listExtraParams: { roleType: 'TENANT' },
          },
          parser: value => ({
            [messageKey]: value ? value.map(item => item.companyOID) : null
          }),
          JSONObjectFormatterParams: ['name', 'companyOID']
        };
        break;
      case 'default_amount_from':
      case 'default_amount_to':
        searchFormOption = {
          dataIndex: messageKey,
          id: 'numberRange' + messageKey,
          label: name,
          component: <NumberRange/>,
          parser: value => ({
            [messageKey]: {
              valueBegin: value && value[0] ? value[0] : null,
              valueEnd: value && value[1] ? value[1] : null
            }
          }),
          tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
        };
        break;
      case 'default_department_group':
      case 'custom_form_department_group':
        break;
      case 'default_user_position':
        searchFormOption = {
          component: 'Input',
          id: messageKey,
          label: name,
          dataIndex: messageKey
        };
        break;
      default:
        searchFormOption = null;
    }
    return searchFormOption
  };

  onGetData = res => {
    let { searchForm, columns } = this.state;
    let approvalMatrixParamsList = [];
    let approvalMatrixColumnsList = [];
    searchForm = [{
      id: 'priority', label: messages('request-4.key250')/*优先级*/, component: 'Input', dataIndex: 'priority',
    },
      {
        id: 'approverOIDList', label: messages('request-4.key391')/*审批人*/, component: 'Selector',
        props: {
          placeholder: messages('common.please.input')/*请输入*/ + messages('request-4.key391')/*审批人*/,
          selectorItem: {
            ...selectorData['user'],
            url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
            label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                messages('request-1.key793')/*待离职员工*/ :
                messages('request-1.key794')/*离职员工*/}）`
              ) :
              ''
            )}`)
          }
        },
        dataIndex: 'approverName',
        parser: value => ({
          approverOIDList: value ? [value] : null
        }),
        JSONObjectFormatterParams: ['fullName', 'userOID']
      }, {
        dataIndex: 'expiredDate',
        id: 'expiredDate',
        label: messages('request-4.key575')/*有效期至*/,
        component: 'DateRangePicker',
        parser: value => ({
          beginDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
          endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
        })
      },];
    columns = [{
      dataIndex: 'priority', title: messages('request-4.key250')/*优先级*/, width: 120,
    }, {
      dataIndex: 'approverName', title: messages('request-4.key391')/*审批人*/, width: 200,
    }, {
      dataIndex: 'expiredDate', title: messages('request-4.key575')/*有效期至*/, width: 200, render: text => {return text || messages('request-4.key243')/*不限*/}
    }, {
      width: 260,
      title: messages('common.operation')/*操作*/, key: 'operation', render: (text, record) => (
        <div>
          <Popconfirm
            title={messages('request-4.key576')/*确认删除？*/}
            onConfirm={(e) => {
              e.stopPropagation();
              this.handleDelete(record)
            }}
          >
            <a onClick={e => {
              e.stopPropagation();
            }}>{messages('common.delete')/*删除*/}</a>
          </Popconfirm>
          <span className="ant-divider"/>
          <a onClick={e => {
            e.stopPropagation();
            this.handleCreate(messages('common.copy')/*复制*/, record, 'copy')
          }}>{messages('common.copy')/*复制*/}</a>
        </div>
      )
    }];
    res && res.map(item => {
      let formatSearchForm = this.formatSearchForm(item.messageKey, item.name);
      item.status === 1 && formatSearchForm && approvalMatrixParamsList.push(formatSearchForm);
      item.status === 1 && approvalMatrixColumnsList.push({
        dataIndex: item.messageKey, title: item.name + ' ' + symbolScopeMap[item.symbols], width: 200,
        render: (text, record) => {
          let name;
          (record.matrixRuleCondition || []).map(condition => {
            if (item.messageKey === condition.messageKey) {
              let list = Array.apply(null, { length: 10 }).map((item, index) =>
                ({ id: String(index + 1), name: chnNumChar[index] }));//部门层级
              if (item.messageKey === 'default_department_level' || item.messageKey === 'custom_form_department_level') {
                if (condition.valueName) {
                  //部门层级是本地的枚举类型 valueName 1-10
                  record[item.messageKey] = list[Number(condition.valueName) - 1]['name'] || '-'
                }
              } else {
                record[item.messageKey] = condition.valueName;
              }
            }
          });
          return record[item.messageKey];
        }
      })
    });
    //动态生成searchForm & columns
    searchForm.splice(1, 0, ...approvalMatrixParamsList);
    columns.splice(1, 0, ...approvalMatrixColumnsList);
    this.setState({ searchForm, columns })
  };

  handleDelete = record => {
    let { selectedRowKeys } = this.state;
    if (record) {
      this.setState({ loading: true, selectedRowKeys: [] });
      workflowMatrixService.deleteConditionDimension([record.approvalMatrixRuleId]).then(res => {
        this.advancedDetailTableRef.getList();
        message.success(messages('common.delete.successful')/*删除成功*/);
        this.setState({ loading: false });
      })
    } else {
      confirm({
        title: messages('request-4.key577',{arg1: selectedRowKeys.length})/*确认删除选中的{arg1}条？*/,
        okText: messages('request-4.key578')/*确认*/,
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.setState({ loading: true });
          workflowMatrixService.deleteConditionDimension(selectedRowKeys).then(res => {
            this.setState({ loading: false, selectedRowKeys: [] });
            this.advancedDetailTableRef.getList();
            message.success(messages('common.delete.successful')/*删除成功*/)
          }).catch(e => {
            this.setState({ loading: false });
            errorMessage(e.response);
          });
        },
        onCancel: () => {
          return false;
        },
    }).catch(err => {
        this.setState({ loading: false });
          errorMessage(err.response);
      })
    }
  }

  getUploadResult = data => {
    let errorData = [];
    let errors = data.errors || {};
    Object.keys(errors).map(error => {
      errors[error].map(index => {
        errorData.push({index, error})
      })
    });
    errorData.sort((a,b) => a.index > b.index);
    errorData = errorData.slice(0, 10);
    return errorData;
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  render() {
    let { activeKey, tableConfig, searchForm, columns, selectedRowKeys, loading } = this.state;

    let rowSelection = wrappedRowSelection({
      limit: 200,
      rowKey: record => record.approvalMatrixRuleId,
      selectedRowKeys
    }, this.onSelectChange);

    return (
      <div className="matrix-detail full-height-page">
        <h2 className="title">{this.props.params.name}</h2>
        <Tabs activeKey={activeKey} onChange={this.onChangeTab}>
          <TabPane tab={messages('request-4.key579')/*条件维度*/} key="condition"/>
          <TabPane tab={messages('request-4.key580')/*矩阵明细*/} key="detail"/>
        </Tabs>
        { activeKey === 'condition' &&
        <SimpleTable
          onRef={ref => this.advancedTableRef = ref}
          {...tableConfig}
          footer={ <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>}
          rowKey="approvalMatrixDimensionRlaId"
          onRow={record => ({
            onClick: () => this.handleEdit(messages('common.edit')/*编辑*/, record)
          })}
          pagination={null}
          onGetData={this.onGetData}
          onGetDataError={e => errorMessage(e.response)}
          service={this.service}
        >
        </SimpleTable>}
        {activeKey === 'detail' &&
        <AdvancedTable searchForm={searchForm}
                       onRef={ref => this.advancedDetailTableRef = ref}
                       rowKey="approvalMatrixRuleId"
                       onGetData={this.onGetDetailListData}
                       service={this.serviceDetailList}
                       onRow={record => ({
                         onClick: () => this.handleCreate(messages('common.edit')/*编辑*/, record,)
                       })}
                       footer={ <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>}
                       columns={columns}
                       rowSelection={rowSelection}
                       loading={loading}>
          <div className="table-header-buttons">
            <Space>
              <Button
                type="primary"
                onClick={() => this.handleCreate()}>
                {messages('common.add')/*添加*/}
              </Button>
              <Importer
                title={messages('common.import')/*导入*/}
                btnName={messages('common.import')/*导入*/}
                modalOptions={{ afterClose: () => this.advancedDetailTableRef.getList() }}
                templateOptions={{
                  templateList: [{
                    templateName: messages('request-4.key581')/*审批矩阵模板*/,
                    downFileName: messages('request-4.key581')/*审批矩阵模板*/,
                    downloadUrl: `/api/approvals/matrix/rule/template/export/${this.props.params.id}`
                  }]
                }}
                uploadOptions={{
                  uploadUrl: `/api/approvals/matrix/rule/import`,
                  listenUrl: `/api/batch/transaction/logs/approval`,
                  uploadParams: {
                    approvalMatrixId: this.props.params.id
                  }
                }}
                uploadResultOptions={{
                  shouldDownloadErrorInfo: true,
                  reimportable: true,
                  showErrorTable: true,
                  errorUrl: `/api/approvals/matrix/rule/failed/export`,
                  getErrorTableVisible: result => result && result.failureEntities > 0
                }}
                totalError={data => data && data.totalEntities ? data.totalEntities : 0}
                errorTableData={data => this.getUploadResult(data)}
              />
              <ExportModal
                type={"btn"}
                exportTitle={messages('request-4.key582')/*导出*/}
                exportType="APPROVAL_MATRIX_RULE_EXPORT_TYPE"
                exportCondition={{
                  approvalMatrixId: this.props.params.id
                }}
                exportCommand={'APPROVAL_MATRIX_RULE_EXPORT_TYPE'}
              />
              <Button type="secondary" disabled={!selectedRowKeys.length > 0} onClick={() => this.handleDelete()}>
                {messages('request-4.key583')/*批量删除*/}
              </Button>
            </Space>
          </div>
        </AdvancedTable>
        }
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    tenantMode: state.main.tenantMode,
    authPolicyAll: state.main.authPolicyAll,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}
const wrappedMatrixDetail = Form.create()(MatrixDetail);
export default connect(mapStateToProps)(wrappedMatrixDetail);
